//
//  Invoice_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 14-10-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "Invoice_ViewController.h"
#import "classGenericCell.h"
#import "CustomCell.h"
#import "dao.h"
#import "AppRecord.h"
#import "IconDownloader.h"

@interface Invoice_ViewController ()

@property (nonatomic, strong) NSMutableDictionary *imageDownloadsInProgress;

@end

@implementation Invoice_ViewController

@synthesize tableViewSearch;
@synthesize dataArraySearch = _dataArraySearch;
@synthesize lblNombreCompleto, lblDireccion, lblCiudad, lblComuna, lblCelular, lblReferencia, lblFormaPago, lblFechaEntrega;
@synthesize lblSubTotal, lblDespacho, lblTotal;
@synthesize json;
@synthesize lblInvoiceNumber;
@synthesize imageObjectsBusqueda = _imageObjectsBusqueda;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"count=%lu", (unsigned long)[_dataArraySearch count]);
    return [_dataArraySearch count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
    //  cell.imgImageView.image = [UIImage imageNamed:@"img_maletin.png"];
    cell.lblTrademark.text = objCell.strTrademark;
    cell.lblTitleLabel.text = objCell.strTitleLabel;
    cell.lblSubtitleLabel.text = objCell.strSubtitleLabel;
    
    cell.lblQty.text = objCell.strQty;
    cell.lblPrice.text = objCell.strPrice;
    
    AppRecord *appRecord = [self.imageObjectsBusqueda objectAtIndex:indexPath.row];
    
    //-----------------------------------------------------------------------------------
    //Leemos
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //1.- Imagen normal
    NSString *strNameImageTmp = @"";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
    
    NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    //-----------------------------------------------------------------------------------
    
    if (image == nil) {
        
        [self startIconDownload:appRecord forIndexPath:indexPath celda:cell];
    }else{
        
        [cell.imgImageView setImage:image];
        
/*
        CGSize itemSize = CGSizeMake(87, 76);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
        CGRect imageRect = CGRectMake(3, 3, itemSize.width, itemSize.height);
        [image drawInRect:imageRect];
        cell.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.imgImageView.frame = CGRectMake(3, 3, 87, 76);
*/
//      [self startIconDownload:appRecord forIndexPath:indexPath celda:cell ];
    }
    
    return cell;
}

- (void) retrieveInvoiceDetail{
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];
    
    _imageObjectsBusqueda = [[NSMutableArray alloc] init];

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    NSString *myString = [prefs stringForKey:@"strNroInvoiceSelected"];

    int intNroInvoice = [ [NSString stringWithFormat:@"%@", myString] intValue];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraNotaVenta.aspx?strJsonBase=JsonDetalleNotaVenta&strIdUsuario=64&strIdResumenNotaVenta=%i", intNroInvoice];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load retrieveInvoiceDetail perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"iddnv":"254", "idp":"375", "sku":"357320", "despro":"Aspiradora eléctrica polvo/agua 10litros APA-1000GR.", "marca":"SINDELEN", "und":"1un.", "med":"34x33x33cm.", "can":"1", "prel":"32748", "neto":"27519", "iva":"5229", "total":"32748", "imagen":"http://cdn.chilemat.com.s3-website-sa-east-1.amazonaws.com/ImagenProductos/375/2119_4.jpg" }]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<json.count; i++)
             {
//               lblComuna.text = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"descom"]];
                 
                 NSString *strTitleLabel = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"despro"]]; //@"Cartera Desigual Fucsia, ideal para paseos livianos y comodos en todo clima. De textura liviana, materiales finos.";
                 NSString *strSubtitleLabel = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"und"]];
                 NSString *strTrademark = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"marca"]]; //@"DESIGUAL";
                 NSString *strIdmark = @"";
                 
                 NSString *strSKU = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"sku"]];
                 NSString *strIdProducto = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"idp"]];
                 NSString *strReviews = @"";
                 NSString *strPrice = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[[NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"total"]] doubleValue]]  ]; //@"$ 26.580 c/u";
                 NSString *strOfferPrice = @"";
                 NSString *strPriceDuplicated = @"";
                 NSString *strDiscount = @"";
                 NSString *strOfferTime = @"";
                 
                 NSString *strCantidadTmp = [NSString stringWithFormat:@"%.0f", [[NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"can"]] floatValue] ];   //%.2f
                 
                 NSString *strQty = strCantidadTmp;
                 
                 AppRecord *appRecord = [[AppRecord alloc] init];
                 
                 classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
               
                 NSLog(@"strImgUrl=%@", [[json objectAtIndex:i] objectForKey:@"imagen"]);
                 
                 appRecord.imageURLString = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"imagen"]];
                 
                 [_imageObjectsBusqueda addObject:appRecord];
                 
                 [_dataArraySearch addObject:objCell];
             }
             
             [self.tableViewSearch reloadData];
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    
    //------------------------------------------
}

- (void)startIconDownload:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath celda:(CustomCell *) celda
{
    IconDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:indexPath];
    
    if (iconDownloader == nil)
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = appRecord;
        [iconDownloader setCompletionHandler:^{
            
            //***
            CGSize itemSize = CGSizeMake(87, 76);
            UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
            CGRect imageRect = CGRectMake(3, 3, itemSize.width, itemSize.height);
            [appRecord.appIcon drawInRect:imageRect];
            celda.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            //***
            
            //          celda.imgImageView.image = appRecord.appIcon;
            celda.imgImageView.frame = CGRectMake(3, 3, 87, 76);
            
            [self.imageDownloadsInProgress removeObjectForKey:indexPath];
            
            //---------------------------------------------------------------------------------------------------
            classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
            
            NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
            NSData* data = UIImageJPEGRepresentation(appRecord.appIcon, 1);
            [data writeToFile:path atomically:YES];
            //---------------------------------------------------------------------------------------------------
            
        }];
        [self.imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
    }
}

- (NSString *) obtenerRutaBD{
    NSString *dirDocs;
    NSArray *rutas;
    NSString *rutaBD;
    
    rutas = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    dirDocs = [rutas objectAtIndex:0];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    rutaBD = [[NSString alloc] initWithString:[dirDocs stringByAppendingPathComponent:@"ecommerce.sqlite"]];
    
    if([fileMgr fileExistsAtPath:rutaBD] == NO){
        [fileMgr copyItemAtPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ecommerce.sqlite"] toPath:rutaBD error:NULL];
    }
    
    return rutaBD;
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

-(NSString*) formatCurrencyValue:(double)value
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setCurrencySymbol:@"$"];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *c = [NSNumber numberWithFloat:value];
    return [numberFormatter stringFromNumber:c];
}

- (void) retrieveInvoiceResume{
    
    dao *objDAO = [[dao alloc] init];
    
    int intIdUsuario = 0;
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    NSString *myString = [prefs stringForKey:@"strNroInvoiceSelected"];
    
    lblInvoiceNumber.text = myString;
    
    int intNroInvoice = [ [NSString stringWithFormat:@"%@", myString] intValue];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraNotaVenta.aspx?strJsonBase=JsonResumenNotaVenta&strIdUsuario=%i&strIdResumenNotaVenta=%i", intIdUsuario, intNroInvoice];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load retrieveInvoiceResume!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"idnv":"90", "tdoc":"39", "idsl":"", "fpag":"1", "desfpag":"CONTADO WEBPAY", "iden":"2", "desen":"No enviado", "idcar":"", "neto":"377433", "iva":"71713", "total":"449146", "idest":"1", "desest":"VIGENTE", "iddir":"36", "direc":"Centenario de San Miguel", "numdir":"935", "idepag":"2", "desepag":"NO PAGADADO", "idciu":"4", "desciu":"Santiago", "idcom":"1", "descom":"Tiltil" }]

             //[{"idnv":"231", "tdoc":"39", "idsl":"", "fpag":"1", "desfpag":"CONTADO WEBPAY", "iden":"2", "desen":"No enviado", "idcar":"592", "neto":"2513", "iva":"477", "total":"2990", "idest":"1", "desest":"VIGENTE", "iddir":"35", "direc":"Los Almendros", "numdir":"243", "idepag":"1", "desepag":"PAGADO", "idciu":"4", "desciu":"Santiago", "idcom":"29", "fechaDespacho":"24/11/2014", "fechaDespachoNumerica":"20141124", "descom":"El Bosque" }]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<json.count; i++)
             {
                 lblDireccion.text = [NSString stringWithFormat:@"%@ %@", [[json objectAtIndex:i] objectForKey:@"direc"], [[json objectAtIndex:i] objectForKey:@"numdir"]];  //

                 lblComuna.text = [NSString stringWithFormat:@"%@, %@", [[json objectAtIndex:i] objectForKey:@"descom"], [[json objectAtIndex:i] objectForKey:@"desciu"]];
//               lblCiudad.text = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"desciu"]];

                 lblCelular.text = [NSString stringWithFormat:@""];

                 lblFormaPago.text = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"desfpag"]];
                 
                 lblFechaEntrega.text = [NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"fechaDespacho"]];
                 
                 lblSubTotal.text = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[[NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"total"]] doubleValue]]  ];

                 lblTotal.text = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[[NSString stringWithFormat:@"%@", [[json objectAtIndex:i] objectForKey:@"total"]] doubleValue]]  ];
             }
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
}

- (void)viewWillAppear:(BOOL)animated {

    NSUInteger intOptionTabBar =  [self.tabBarController selectedIndex];

    //Si esta comprando parado en el carro de compra y llega a la orden no hay volver atras
    if (intOptionTabBar == 2) {

        [self.backBarButtonItem setImage:[UIImage imageNamed:@"icono_atras_transparente.png"]];
        
        [self.backBarButtonItem setEnabled:NO];
    }
    
//Datos del cliente
    [self retrieveInvoiceResume];
    
//Productos de la Orden de compra
    [self retrieveInvoiceDetail];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)BackToInvoiceList:(id)sender {
    
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];

}


@end


